package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.audit.baidu.BaiduImageScan;
import com.heima.audit.baidu.BaiduTextScan;
import com.heima.audit.tess4j.Tess4jClient;
import com.heima.feign.apArticle.client.ApArticleFeignClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.temporal.TemporalUnit;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private BaiduTextScan baiduTextScan;

    @Autowired
    private BaiduImageScan baiduImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleFeignClient apArticleFeignClient;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;

    @Autowired
    private Tess4jClient tess4jClient;


    /**
     * 审核自媒体文章
     * 主方法
     *
     * @param newsId 自媒体文章id
     */
    @Override
    @Async//使用异步线程
    @Transactional
    public void autoScanWmNews(Integer newsId) {
        //1.非空判断
        if (newsId == null) {
            return;
        }
        //2.根据文章id查询wm_news
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null) {
            return;
        }

        //2.5 抽取的第一个方法，获取所有的文本和图片
        Map<String, Object> resultMap = getTextAndImages(wmNews);

        //2.6抽取第五个方法，审核标题 内容
        Boolean sensitiveScan = scanSensitiveScan(wmNews, (String) resultMap.get("content"));
        if (!sensitiveScan) {
            return;
        }


        //3.抽取的第二个方法，百度云审核文本内容
        Boolean textFlag = scanText(wmNews, (String) resultMap.get("content"));
        if (!textFlag) {
            return;
        }
        //4.抽取的第三个方法，百度云审核图片
        Boolean imageFlag = scanImage(wmNews, (List<String>) resultMap.get("imageList"));
        if (!imageFlag) {
            return;
        }
        //5.审核通过，抽取的第四个方法，保存三剑客
        ResponseResult result = saveArticleFromNews(wmNews);

        //6.修改wm_news状态=9
        if (result.getCode().equals(200)) {
            wmNews.setArticleId(Long.valueOf(result.getData().toString()));
            updateWmNews(wmNews, (short) 9, "审核发布成功");
        }

    }

    private Boolean scanSensitiveScan(WmNews wmNews, String context) {
        Boolean flag = true;
        //1.获取所有的敏感词
        List<WmSensitive> selectList = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitives = selectList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //2.初始化敏感词
        SensitiveWordUtil.initMap(sensitives);

        //3.匹配文章里的敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(context);
        //4.大小大于0，审核不通过
        if (map.size() > 0) {
            updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容" + map);
            flag = false;
        }
        return flag;
    }

    /**
     * 抽取的第四个方法，保存三剑客
     *
     * @param wmNews
     */
    private ResponseResult saveArticleFromNews(WmNews wmNews) {
        //1.拷贝属性， wmNews 到 apArticleDto
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        //2.补全属性
        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        dto.setAuthorName(wmUser.getName());

        //频道
        dto.setChannelId(wmNews.getChannelId());
        WmChannel wmChannel = wmChannelMapper.selectById(dto.getChannelId());
        dto.setChannelName(wmChannel.getName());

        //布局
        dto.setLayout(wmNews.getType());

        //创建时间
        dto.setCreatedTime(new Date());

        //设置行为数量默认为0
        dto.setViews(0);
        dto.setLikes(0);
        dto.setComment(0);
        dto.setCollection(0);

        ResponseResult result = apArticleFeignClient.save(dto);
        return result;
    }

    /**
     * 抽取的第四个方法，审核图片
     *
     * @param wmNews
     * @param imageList 图片地址集合
     * @return
     */
    private Boolean  scanImage(WmNews wmNews, List<String> imageList) {

        Boolean flag = true;

        //1.非空判断
        if (imageList != null && imageList.size() > 0) {
            //2.图片去重
            imageList = imageList.stream().distinct().collect(Collectors.toList());
            //3.遍历图片
            try {
                for (String path : imageList) {
                    //3.1 minio下载图片
                    byte[] bytes = fileStorageService.downLoadFile(path);

                    //识别图片里的文字
                    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                    BufferedImage image = ImageIO.read(in);
                    String doOCR = tess4jClient.doOCR(image);

                    //匹配文字是否有敏感词
                    Boolean scanImage = scanSensitiveScan(wmNews, doOCR);
                    if (!scanImage) {
                        return scanImage;
                    }

                    //3.2百度云审核图片
                    Integer status = baiduImageScan.imageScan(bytes);
                    //3.3 判断状态，并修改wm_news
                    //若为2，不合规
                    if (status == 2) {
                        updateWmNews(wmNews, (short) 2, "图片中可能包含不合规的内容");
                        flag = false;
                        break;
                    } //若为3，疑似合规
                    else if (status == 3) {
                        updateWmNews(wmNews, (short) 3, "图片中可能包含疑似不合规的内容,请通过人工审核");
                        flag = false;
                        break;
                    }//若为4 失败
                    else if (status == 4) {
                        updateWmNews(wmNews, (short) 2, "图片中可能包含审核失败的内容");
                        flag = false;
                        break;
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return flag;
    }

    /**
     * 抽取的第二个方法，百度云审核文本内容
     *
     * @param wmNews
     * @param content
     * @return
     */
    private Boolean scanText(WmNews wmNews, String content) {

        Boolean flag = true;
        //1.调用百度云审核的接口
        Integer status = baiduTextScan.textScan(content);

        //2.1判断状态，并修改wm_news
        //为2，不合规，
        if (status == 2) {
            updateWmNews(wmNews, (short) 2, "内容中可能包含不合规的词汇");
            flag = false;
        }//为3，疑似合规
        else if (status == 3) {
            updateWmNews(wmNews, (short) 3, "内容中可能包含疑似不合规的词汇,请通过人工审核");
            flag = false;
        }//为4，失败
        else if (status == 4) {
            updateWmNews(wmNews, (short) 2, "内容中可能包含审核失败的词汇");
            flag = false;
        }
        return flag;
    }

    /**
     * 抽取方法 修改wm_news
     *
     * @param wmNews
     * @param status
     * @param message
     */
    private void updateWmNews(WmNews wmNews, short status, String message) {
        wmNews.setStatus(status);
        wmNews.setReason(message);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 抽取的第一个方法，先抽取所有的文本和图片
     *
     * @param wmNews
     * @return
     */
    private Map<String, Object> getTextAndImages(WmNews wmNews) {

        StringBuilder sb = new StringBuilder();//标题和内容
        List<String> imageList = new ArrayList<>();//从内容中获取的图片，传参的封面图片

        //1.获取标题
        String title = wmNews.getTitle();
        sb.append(title);

        String content = wmNews.getContent();
        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        for (Map map : contentList) {
            //2.获取图片
            if (map.get("type").equals("image")) {
                imageList.add((String) map.get("value"));
            }
            //3.获取内容
            if (map.get("type").equals("text")) {
                sb.append((String) map.get("value"));
            }
        }
        //4.获取封面图片
        String images = wmNews.getImages();
        if (images != null) {
            imageList.addAll(Arrays.asList(images.split(",")));
        }


        //5.封装数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", sb.toString());
        resultMap.put("imageList", imageList);
        return resultMap;
    }

}